package com.lagou.edu.course.remote;

import com.lagou.edu.course.entity.Course;
import com.lagou.edu.course.service.ICourseService;
import com.lagou.edu.dto.CourseDTO;
import com.lagou.edu.notice.dto.QueueMsgDTO;
import com.lagou.edu.notice.remote.MqRemoteService;
import com.lagou.edu.remote.CourseRemoteService;
import com.lagou.edu.response.ResponseDTO;
import com.lagou.edu.util.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseService implements CourseRemoteService {
    @Autowired
    private ICourseService courseService;

    @Autowired
    private MqRemoteService mqRemoteService;

    @GetMapping("/getAllCourses")
    public List<CourseDTO> getAllCourses() {
        List<Course> promotionSpaceList = courseService.list();
        return ConvertUtil.convertList(promotionSpaceList, CourseDTO.class);
    }

    @Override
    @PostMapping("/saveOrUpdate")
    public ResponseDTO saveOrUpdateCourse(CourseDTO courseDTO) {
        Course entity = ConvertUtil.convert(courseDTO, Course.class);

        if(entity.getId() == null){
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            entity.setIsDel(false);
        }else {
            entity.setUpdateTime(new Date());
        }

        ResponseDTO responseDTO = null;
        try {
            courseService.saveOrUpdate(entity);
            responseDTO = ResponseDTO.success();
        }catch (Exception e){
            responseDTO = ResponseDTO.ofError(e.getMessage());
            e.printStackTrace();
        }
        return responseDTO;
    }

    @PostMapping("/swithOnlineStatus")
    public ResponseDTO switchOnlineStatus(@RequestBody CourseDTO courseDTO) {
        System.out.println(">>>courseId: " + courseDTO.getId());
        Course tCourse = courseService.getById(courseDTO.getId());
        tCourse.setStatus(courseDTO.getStatus());

        ResponseDTO responseDTO = null;
        if (courseService.updateById(tCourse)) {
            responseDTO = ResponseDTO.success();
            if (tCourse.getStatus() == 1) {
                try {
                    String msg = tCourse.getCourseName();
                    QueueMsgDTO queueMsgDTO = new QueueMsgDTO();
                    queueMsgDTO.setMessage(msg);
                    mqRemoteService.receive(queueMsgDTO);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        } else {
            responseDTO = ResponseDTO.ofError("调整上下架状态失败！");
        }

        return responseDTO;
    }
}
